package pl.un4giv3n.mightvsmagic.action;

import javax.persistence.EntityManager;

import pl.un4giv3n.mightvsmagic.entity.Action;
import pl.un4giv3n.mightvsmagic.entity.ActionType;
import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.Reward;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.utils.ActionUtil;
import pl.un4giv3n.mightvsmagic.utils.ActivityLogUtil;
import pl.un4giv3n.mightvsmagic.utils.ClanUtil;

/**
 * @author andrzejewskia
 * work - user gains gold for working
 */
public class WorkAction extends PersistenceAction {

	private static final long serialVersionUID = 1L;
	/**
	 * current user action
	 */
	private Action currentAction;
	/**
	 * session user
	 */
	private User user;
	/**
	 * performed work type
	 */
	private WorkType workType;
	/**
	 * performed action type
	 */


	/**
	 * @author andrzejewskia
	 * this is an enum indicating if the work was "magic" or "might"
	 */
	private enum WorkType {
		FIGHT, MAGIC
	}

	/* (non-Javadoc)
	 * @see pl.un4giv3n.mightvsmagic.action.PersistenceAction#execute()
	 */
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		currentAction = user.getCurrentAction();
		if (currentAction == null || currentAction.equals(Action.NO_ACTION)) {
			if (workType == null) {
				addActionError("Nie wybrano typu pracy!");
				return INPUT;
			}
			entityManager.getTransaction().begin();
			currentAction = new Action(ActionType.WORK, createReward());
			user.setCurrentAction(currentAction);
			UserActivity activity = ActivityLogUtil.createActivity(ActivityType.WORK_START, user.getId());
			entityManager.persist(activity);
			entityManager.merge(user);
			entityManager.flush();
			entityManager.getTransaction().commit();
			entityManager.close();
			return ACTION_START;
		} else {
			return "redirect";
		}
	}

	private Reward createReward() {
		double random = Math.random();
		int exp = random > 0.7 ? 1 : 0;
		return new Reward(calculateAdditionalGold(),
				workType == WorkType.FIGHT ? exp : 0,
				workType == WorkType.MAGIC ? exp : 0);
	}

	private long calculateAdditionalGold() {
		long bonus = 0;
		if(workType == WorkType.FIGHT){
			bonus=user.getFightExp()/100;
		}else{
			bonus=user.getMagicExp()/100; 
		}
		if(user.getClan() != null){
			bonus+=ClanUtil.getGoldBonus(user.getClan());
		}
		return Math.round(Math.random() * 1000 + bonus);
	}


	public String getActionEnd() {
		return ActionUtil.generateStartMessage(currentAction, user);
	}

	public void setWorkType(String workType) {
		this.workType = WorkType.valueOf(workType);
	}

	public User getUser() {
		return user;
	}
}
